package com.itheima.crm.controller;

import java.io.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.itheima.common.utils.FileOperate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.itheima.common.utils.Page;
import com.itheima.crm.pojo.BaseDict;
import com.itheima.crm.pojo.RiZhi;
import com.itheima.crm.pojo.YuanGong;
import com.itheima.crm.pojo.gongwen;
import com.itheima.crm.service.ApplicationService;
import com.itheima.crm.service.BaseDictService;
import com.itheima.crm.service.RiZhiService;
import com.itheima.crm.service.YuanGongService;
import com.itheima.crm.service.gongwenService;

/**
 * 客户管理
 * 
 * @author lx
 *
 */
@Controller
public class GongWenController {
	@Autowired
	private gongwenService gongwenService;
	@Autowired
	private BaseDictService baseDictService;
	@Autowired
	private YuanGongService yuangongService;
	@Autowired
	private ApplicationService applicationService;
	@Autowired
	private RiZhiService rizhiService;
	

	public gongwenService getGongwenService() {
		return gongwenService;
	}

	public void setGongwenService(gongwenService gongwenService) {
		this.gongwenService = gongwenService;
	}

	public BaseDictService getBaseDictService() {
		return baseDictService;
	}

	public void setBaseDictService(BaseDictService baseDictService) {
		this.baseDictService = baseDictService;
	}

	public YuanGongService getYuangongService() {
		return yuangongService;
	}

	public void setYuangongService(YuanGongService yuangongService) {
		this.yuangongService = yuangongService;
	}

	public ApplicationService getApplicationService() {
		return applicationService;
	}

	public void setApplicationService(ApplicationService applicationService) {
		this.applicationService = applicationService;
	}

	public RiZhiService getRizhiService() {
		return rizhiService;
	}

	public void setRizhiService(RiZhiService rizhiService) {
		this.rizhiService = rizhiService;
	}

	@RequestMapping(value = "/GongWen")
	public String list(HttpServletRequest request, gongwen vo, Model model) {

		List<BaseDict> gwtypeType = baseDictService.selectBaseDictListByCode("007");

		model.addAttribute("gwtypeType", gwtypeType);

		// 通过四个条件 查询分页对象

		Page<gongwen> page = gongwenService.selectgongwen(vo);

		model.addAttribute("page", page);

		return "GongWen";
	}

	@RequestMapping(value = "/GongWenNew")
	public ModelAndView newlist(HttpServletRequest request, gongwen vo, Model model) {
		List<BaseDict> gwtypeType = baseDictService.selectBaseDictListByCode("007");

		model.addAttribute("gwtypeType", gwtypeType);

		ModelAndView c = new ModelAndView();
		c.setViewName("GongWenNew");
		RiZhi a=new RiZhi();
		request.getSession().getAttribute("ygid");
		a.setYgid((Integer)request.getSession().getAttribute("ygid"));
		a.setYgname((String)request.getSession().getAttribute("ygname"));
		a.setInsertdate(new Date());
		System.out.println(a.getInsertdate());
		a.setDetial("新建公文页面");
		rizhiService.insertApplication(a);
		
		return c;
	}

	/**
	 * 文件上传
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/insertGongWen", method = RequestMethod.POST)
	public void sUpload(@RequestParam(value = "location", required = false) MultipartFile mulFile,
			HttpServletRequest request, HttpServletResponse response) {

		gongwen gongwen = new gongwen();
		 HttpSession session=request.getSession(false);
		String loginname = (String) session.getAttribute("loginname");
		String loginpw = (String) session.getAttribute("loginpw");

		Integer applicant_id = applicationService.selectYGidBylogin(loginname, loginpw);

		System.out.println(applicant_id);

		YuanGong loginer = yuangongService.selectYuanGongByYGid(applicant_id);
		System.out.println(loginer.toString());

		String docPath = "G:\\OA\\"; // 磁盘绝对路径根路径
		String absPath = null;// 绝对路径
		String newFileName = null;// 文档名
		String virPath = "/doc/";// 数据库存储虚拟相对路径
		String organization = loginer.getOrganization();
		Integer ygid = loginer.getYgid();
		String ygname = loginer.getYgname();

	

		gongwen.setGwid(Integer.parseInt(request.getParameter("gwid")));
		gongwen.setGwname(request.getParameter("gwname"));
		gongwen.setGwtype(request.getParameter("gwtype"));
		gongwen.setUpdateman(request.getParameter("updateman"));
		System.out.println(request.getParameter("updatetime"));

		gongwen.setUpdatetime(new Date());
		/* gongwen.setUpdatetime(request.getParameter("updatetime")); */
		String originalFileName = null;
		originalFileName = mulFile.getOriginalFilename();
		System.out.println("oriname" + originalFileName);
		boolean isUploadSuccess = false;
		PrintWriter out = null;
		File newFile = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 上传文件之前，删除pdf文件
		FileOperate.delFile(docPath + organization + "\\" + ygid + ".pdf");
		System.out.println("文件上传前已删除pdf:" + docPath + organization + "\\" + ygid + ".pdf");
		// 查询指定id文档是否已存在，不存在才能正常上传文档
		if (gongwenService.queryDocByDocId(gongwen.getGwid()) == null) {
			System.out.println("执行到这里----------1-----------");
			/*
			 * // 继续判断是否存在对应文档的修改意见，不存在才能正常上传
			 * if(studentService.queryDocByDocId(docAdviceId)==null) {
			 */
			/* System.out.println("执行到这里----------2-----------"); */
			// 判断表单信息，文件类型和表单信息不为空，才能正常上传
			if (mulFile != null && originalFileName != null && originalFileName.length() > 0) {
				System.out.println("执行到这里----------2-----------");
				// 开始上传，接收参数，文件
				newFileName = gongwen.getGwid() + originalFileName.substring(originalFileName.lastIndexOf("."));// 新文件名
				absPath = docPath + organization + "\\" + ygname + "\\";// 绝对路径
				newFile = new File(absPath + newFileName);
				System.out.println(absPath + newFileName);
				if (!newFile.exists()) {
					System.out.println("执行到这里----------3-----------");
					// 路径判断
					File dir = new File(absPath);
					dir.mkdirs();
				}
				// 将内存中的数据写入磁盘
				try {
					mulFile.transferTo(newFile);
				} catch (IllegalStateException | IOException e) {
					e.printStackTrace();
				}
				virPath += organization + "/" + ygname + "/" + newFileName;
				System.out.println("virPath:" + virPath);
				gongwen.setLocation(virPath);
				// 设置上传标记
				 RiZhi c=new RiZhi();
					request.getSession().getAttribute("ygid");
					c.setYgid((Integer)request.getSession().getAttribute("ygid"));
					c.setYgname((String)request.getSession().getAttribute("ygname"));
					c.setInsertdate(new Date());
					System.out.println(c.getInsertdate());
					c.setDetial("上传公文");
					rizhiService.insertApplication(c);
				isUploadSuccess = gongwenService.insertgongwen(gongwen);
			}
			if (isUploadSuccess) {
				System.out.println("执行到这里----------5-----------");

				out.println("<script>alert('UpLoad Success!');history.back();</script>");
				// str="{\"info\":\"提交信息成功!\"}";
			} else {
				System.out.println("执行到这里----------6-----------");
				out.println("<script>alert('UpLoad Failed!');history.back();</script>");
			}
		}

	}

	/**
	 * 文件下载功能
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/Gongwen/downloadGongWen")
	public void downloadGongWen(HttpServletRequest request, HttpServletResponse response, Integer id) throws Exception {
	      //模拟文件,myfile.txt为需要下载的文件  
	    	//studentService.queryAllDoc(stuLogin)
	        /*String location = request.getSession().getServletContext().getRealPath("doc"); */
	        //System.out.println("Location"+location);
	        //获取输入流  
		
		     gongwen a=gongwenService.selectgongwenById(id);
	    	String location=a.getLocation().substring(4).replaceAll("/","\\\\\\\\");
	    	System.out.println("location:"+location);
	    	String fileName = "G:\\OA\\"+location;
	        InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));  
	        //假如以中文名下载的话  
	        //String filename = "下载文件.txt";  
	        //转码，免得文件名中文乱码  
	       // filename = URLEncoder.encode(filename,"UTF-8");  
	        //设置文件下载头  
	        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);    
	        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型    
	        response.setContentType("multipart/form-data");   
	        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());  
	        int len = 0;  
	        while((len = bis.read()) != -1){  
	            out.write(len);  
	            out.flush();  
	        }  
	        out.close();  
	        bis.close();
	        RiZhi c=new RiZhi();
			request.getSession().getAttribute("ygid");
			c.setYgid((Integer)request.getSession().getAttribute("ygid"));
			c.setYgname((String)request.getSession().getAttribute("ygname"));
			c.setInsertdate(new Date());
			System.out.println(c.getInsertdate());
			c.setDetial("下载公文");
			rizhiService.insertApplication(c);
	    } 

	
	@RequestMapping(value = "/Gongwen/deleteGongwen")
	public @ResponseBody String deleteGongWen(Integer id,HttpServletRequest request) {
		gongwenService.deleteDocById(id);
		  RiZhi c=new RiZhi();
			request.getSession().getAttribute("ygid");
			c.setYgid((Integer)request.getSession().getAttribute("ygid"));
			c.setYgname((String)request.getSession().getAttribute("ygname"));
			c.setInsertdate(new Date());
			System.out.println(c.getInsertdate());
			c.setDetial("删除公文");
			rizhiService.insertApplication(c);
		return "OK";
	}

	@InitBinder
	protected void init(HttpServletRequest request, ServletRequestDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
	}

}
